﻿// Gateway.Api 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Aurora.AI.Domain.Domain;
using Aurora.AI.Gateway.Models.UserLimit;
using Aurora.AI.SqlSugar.Framework.Repositories;

namespace Aurora.AI.Gateway.Services;
/// <summary>
/// 用户ai 限制服务
/// </summary>
/// <param name="repository"></param>
public class UserAILimitService(IRepository<UserAILimit> repository)
{
    /// <summary>
    /// 根据用户id 获取 用户下的 限制请求
    /// </summary>
    /// <param name="userId"></param>
    /// <returns></returns>
    public async Task<UserAILimit> GetUserLimit(string userId)
    {
        Task<UserAILimit> firstAsync = repository.GetFirstAsync(x => x.UserId.Equals(userId));
        return await firstAsync;
    }

    /// <summary>
    /// 获取用户的 限制请求
    /// </summary>
    /// <param name="userIds"></param>
    /// <returns></returns>
    public async Task<List<UserAILimit>> GetListByUserIds(List<string> userIds)
    {
        return await repository.GetListAsync(x => x.IsDeleted == false && userIds.Contains(x.UserId));
    }



    public async Task<bool> CreateAsync(UserLimitCreateRequest request)
    {
        var user = await repository.GetFirstAsync(x => x.UserId.Equals(request.UserId) && x.IsDeleted == false);
        if (user == null)
        {
            var entity = new UserAILimit()
            {
                CreationTime = DateTime.Now,
                ModificationTime = DateTime.Now,
                Modifier = request.OperatorId,
                Creator = request.OperatorId,
                UserId = request.UserId,
                ConsumeToken = 0,
                RequestCount = 0,
                ResidualCredit = (long)(request.ResidualCredit * 500000L), // 这里需要将 金钱转换为 token 数量 long类型
                IsDeleted = false
            };
            // 在这里需要生成key
            await repository.InsertAsync(entity);
        }
        else
        {
            user.ResidualCredit = (long)(request.ResidualCredit * 500000L);
            user.Modifier = request.OperatorId;
            user.ModificationTime = DateTime.Now;
            user.IsDeleted = false;
            await repository.UpdateAsync(user);
        }
        return true;
    }

    public async Task<bool> RemoveAsync(string id)
    {
        return await repository.DeleteAsync(id);
    }


    /// <summary>
    /// 用户消费
    /// </summary>
    /// <param name="id"></param>
    /// <param name="consume"></param>
    /// <param name="consumeToken"></param>
    /// <param name="token"></param>
    /// <param name="channelId"></param>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<bool> ConsumeAsync(string id, long consume, int consumeToken, string? token, string channelId,
        string model)
    {
        // string key = "FreeModal:" + id;
        UserAILimit userAiLimit = await repository.GetFirstAsync(x => x.UserId.Equals(id) && x.IsDeleted == false && x.ResidualCredit >= consume);
        if (userAiLimit == null)
        {
            return false;
        }

        userAiLimit.ResidualCredit -= consume;
        userAiLimit.RequestCount += 1;
        userAiLimit.ConsumeToken += consumeToken;
        var result = await repository.UpdateAsync(userAiLimit);
        if (!string.IsNullOrEmpty(token))
        {
            await repository.GetDb().Updateable<Token>()
                .SetColumns(x => x.RemainQuota == x.RemainQuota - consume)
                .SetColumns(x => x.AccessedTime == DateTime.Now).SetColumns(x => x.UsedQuota == x.UsedQuota + consume)
                .Where(x => x.Key.Equals(token))
                .ExecuteCommandAsync();
        }

        await repository.GetDb().Updateable<Domain.Domain.ChatChannel.Aggregates.ChatChannel>()
            .SetColumns(x => x.Quota == x.Quota + consume)
            .Where(x => x.Id.Equals(channelId))
            .ExecuteCommandAsync();
        return result;
    }
}
